package amani.wechat.platform.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.core.util.HttpRequestProxy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import amani.wechat.platform.controller.model.ActivateCard;
import amani.wechat.platform.controller.model.AddCardReturnData;
import amani.wechat.platform.controller.model.Result;
import amani.wechat.platform.services.ICommonService;
import amani.wechat.platform.utils.WxUtils;
import amani.wechat.platform.webserviceClient.Cardinfo;
import amani.wechat.platform.webserviceClient.VirtualCard;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Controller
@RequestMapping("/UCenter")
public class UCenterController {
	@Resource(name="CommonService") 
	ICommonService commonService ;

	@RequestMapping("/Index")
	public String Index() {
		return "ucenter/index";
	}
	
	/**
	 * 我的账号
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/my")
	public String my(String cardno, HttpSession session, Model model) {
		String openId = ObjectUtils.toString(session.getAttribute("openid"));
		if(StringUtils.isNotBlank(openId)){
			String[] cards = commonService.loadAllCard("001", openId);
			model.addAttribute("cards", cards);
			cardno = StringUtils.isNotBlank(cardno)?cardno:"";
			Cardinfo cardinfo = commonService.loadCardInfobyOpenid("001", openId, cardno);
			model.addAttribute("member", cardinfo);
		}
		return "ucenter/my";
	}
	
	/**
	 * 修改我的账号
	 * @param model
	 * @return
	 */
	@RequestMapping("/account")
	public String account(String cardno, String memberImageUrl, String membername, String memberpaperworkno,
				String memberphone, String memberbirthday, String password, Model model) {
		model.addAttribute("cardno", cardno);
		model.addAttribute("memberImageUrl", memberImageUrl);
		model.addAttribute("membername", membername);
		if(StringUtils.isNotBlank(memberphone)){
			model.addAttribute("memberphone", StringUtils.replace(memberphone, StringUtils.substring(memberphone, 3, 7), "****"));
			model.addAttribute("membermobile", memberphone);
		}
		if(StringUtils.isNotBlank(memberbirthday)){
			StringBuffer birthday = new StringBuffer(memberbirthday);
			birthday.insert(4, "-").insert(7, "-");
			model.addAttribute("memberbirthday", birthday);
		}
		if(StringUtils.isNotBlank(memberpaperworkno)){
			int len = memberpaperworkno.length();
			String pcid = StringUtils.substring(memberpaperworkno, 0, 4) +"*******"+
							(len==15 ? "":"***")+ StringUtils.substring(memberpaperworkno, len-4);
			model.addAttribute("memberpcid", pcid);
		}
		model.addAttribute("password", password);
		return "ucenter/account";
	}
	
	/**
	 * 修改密码
	 * @return
	 */
	@RequestMapping("/changePwd")
	@ResponseBody
	public String changePwd(String cardno, String password, String checkcode, HttpSession session) {
		String sendcode = ObjectUtils.toString(session.getAttribute("mobilecode"));
		if(StringUtils.equals(sendcode, checkcode)){
			String openId = ObjectUtils.toString(session.getAttribute("openid"));
			boolean isok = commonService.changePassword(openId, cardno, password);
			return isok ? "1":"2";
		}else{
			return "0";
		}
	}
	
	/**
	 * 在线预约
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/orders")
	public String orders(HttpSession session, Model model) {
		String openId = ObjectUtils.toString(session.getAttribute("openid"));
		String result = commonService.loadOrderDetal(openId);
		if(StringUtils.isNotBlank(result)){
			Gson gson = new Gson();
			List<Map<String, Object>> orders = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>(){}.getType());
			model.addAttribute("orders", orders);
		}
		return "ucenter/orders";
	}
	
	/**
	 * 预约详情
	 * @return
	 */
	@RequestMapping("/order")
	public String order(String json, Model model) {
		if(StringUtils.isNotBlank(json)){
			Gson gson = new Gson();
			Map<String, Object> order = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
			try {
				String staffname = new String(order.get("staffname").toString().getBytes("ISO-8859-1"), "UTF-8");
				order.put("staffname", staffname);
				String address = new String(order.get("address").toString().getBytes("ISO-8859-1"), "UTF-8");
				order.put("address", address);
				String projectname = new String(order.get("orderfactproject").toString().getBytes("ISO-8859-1"), "UTF-8");
				order.put("projectname", projectname);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			model.addAttribute("order", order);
		}
		return "ucenter/order";
	}
	
	/**
	 * 取消预约
	 * @param strBillId
	 * @return
	 */
	@RequestMapping("/canceOrder")
	@ResponseBody
	public boolean canceOrder(String strBillId){
		return commonService.updOrderState(strBillId);
	}
	
	/**
	 * 订单列表
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/online")
	public String online(HttpSession session, Model model) {
		String openId = ObjectUtils.toString(session.getAttribute("openid"));
		List<Map<String, Object>> orders = commonService.loadWxOrders(openId, "");
		model.addAttribute("orders", orders);
		return "ucenter/online";
	}
	
	/**
	 * 订单详情
	 * @return
	 */
	@RequestMapping("/booking")
	public String booking(String json, Model model) {
		if(StringUtils.isNotBlank(json)){
			Gson gson = new Gson();
			Map<String, Object> order = gson.fromJson(json, new TypeToken<Map<String, Object>>(){}.getType());
			try {
				String address = new String(order.get("address").toString().getBytes("ISO-8859-1"), "UTF-8");
				order.put("address", address);
				String companyaddress = new String(order.get("companyaddress").toString().getBytes("ISO-8859-1"), "UTF-8");
				order.put("companyaddress", companyaddress);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			model.addAttribute("order", order);
		}
		return "ucenter/booking";
	}
	
	/**
	 * 消费列表
	 * @return
	 */
	@RequestMapping("/consumes/{cardno}")
	public String consumes(@PathVariable String cardno, Model model){
		String result = commonService.loadcCardaccountchangehistories(cardno);
		if(StringUtils.isNotBlank(result)){
			Gson gson = new Gson();
			List<Map<String, Object>> consumes = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>(){}.getType());
			model.addAttribute("consumes", consumes);
		}
		return "ucenter/consumes";
	}
	/**
	 * 消费明细
	 * @return
	 */
	@RequestMapping("/consume")
	public String consume(String cardno, Model model){
		return "ucenter/consume";
	}
	
	/**
	 * 疗程列表
	 * @return
	 */
	@RequestMapping("/courses/{cardno}")
	public String courses(@PathVariable String cardno, Model model){
		String result = commonService.loadCardproaccounts("001", cardno);
		if(StringUtils.isNotBlank(result)){
			Gson gson = new Gson();
			List<Map<String, Object>> courses = gson.fromJson(result, new TypeToken<List<Map<String, Object>>>(){}.getType());
			model.addAttribute("courses", courses);
		}
		return "ucenter/courses";
	}
	/**
	 * 疗程明细
	 * @return
	 */
	@RequestMapping("/course")
	public String course(Model model){
		return "ucenter/course";
	}
	
	/**
	 * 用户绑定跳转到页面
	 * @return
	 */
	@RequestMapping("/index/binding")
	public String binding() {
		return "ucenter/binding";
	}
	
	/**
	 * 获取验证码
	 * @param mobile
	 * @param session
	 * @return
	 */
	@RequestMapping("/index/getmobilecode")
	@ResponseBody
	public boolean getmobilecode(String mobile,HttpSession session) {
		boolean res = true;
		String mobilecode = getRandomCode();
		session.setAttribute("mobilecode", mobilecode);
		String message = "您的验证码是 "+mobilecode+"【阿玛尼护肤造型】";
		commonService.sendMessage(mobile, message);
		return res;
	}
	/**
	 * 验证卡号和手机号
	 * @param realname
	 * @param cardcode
	 * @param mobile
	 * @return
	 */
	@RequestMapping("/index/checkcard")
	@ResponseBody
	public Result checkcard(String realname,String cardcode,String mobile) {
		Result res = new Result();
		List<Cardinfo> tmp = commonService.loadCardInfos(mobile, cardcode);
		if(tmp.size()>0){
			res.setIsok(true);
		}else{
			res.setIsok(false);
			res.setError("输入卡号信息或者手机信息有误");
		}
		return res;
	}
	
	@RequestMapping("/index/binding2")
	@ResponseBody
	public Result binding2(String realname,String cardcode,String mobile,String checkcode,HttpSession session) {
		Result res = new Result();
		if((session.getAttribute("mobilecode")+"").equals(checkcode)){
			String openid = session.getAttribute("openid")+"";
			boolean isok = commonService.bindingCard(cardcode, realname, mobile, openid);
			res.setIsok(isok);
			res.setError("绑定失败");
			session.setAttribute("electronicCardNo", cardcode);
		}else{
			res.setIsok(false);
			res.setError("验证码错误");
		}
		return res;
	}
	@RequestMapping("/index/electronicCard")
	public String electronicCard(){
		return "ucenter/electronicCard";
	}
	//注册电子卡
	@RequestMapping("/index/registElectronic")
	@ResponseBody
	public Result registElectronic(String realname,String cardcode,String mobile,int sex,String checkcode,HttpSession session) {
		Result res = new Result();
		if((session.getAttribute("mobilecode")+"").equals(checkcode)){
			String openid = session.getAttribute("openid")+"";
			VirtualCard aVirtualCard = commonService.saveVirtualCard(openid, mobile, sex);
			//System.out.println("electronicCardNo:"+aVirtualCard.getCardno().getValue());
			session.setAttribute("electronicCardNo", aVirtualCard.getCardno().getValue());
			boolean isok = false;
			if(aVirtualCard!=null)
				isok = commonService.bindingCard(aVirtualCard.getCardno().getValue(), realname, mobile, openid);
			res.setIsok(isok);
		}else{
			res.setIsok(false);
			res.setError("验证码错误");
		}
		return res;
	}
	
	/**
	 * 员工绑定页面
	 * @return
	 */
	@RequestMapping("/sendCard")
	public String sendCard() {
		return "ucenter/sendCard";
	}
	
	@RequestMapping("/sendCard/send") 
	@ResponseBody 
	public AddCardReturnData SendCard(HttpServletRequest request) throws WexinReqException {
		AddCardReturnData result=new AddCardReturnData();
		try{
			result=new AddCardReturnData();
			result.setCardId("prCjajnQ1iPwjJHEZ0i8DbHYZgdo"); 
			String openid=(String)request.getSession().getAttribute("openid");
			String electronicCardNo = request.getSession().getAttribute("electronicCardNo")==null? null:request.getSession().getAttribute("electronicCardNo").toString();
			if(null==electronicCardNo){
				ActivateCard a = commonService.loadAccount(openid).get(0);
				electronicCardNo = a.getCode();
			}
			request.getSession().setAttribute("electronicCardNo",electronicCardNo);
			activeCode(electronicCardNo,"prCjajnQ1iPwjJHEZ0i8DbHYZgdo");
			System.out.println(electronicCardNo);
			result.setCardExt(WxUtils.getCardExt("prCjajnQ1iPwjJHEZ0i8DbHYZgdo",electronicCardNo, openid)); 
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
		
	}
	
	private void activeCode(String code,String card_id) throws WexinReqException{
		try{
			JSONObject obj=new JSONObject();
			HttpRequestProxy proxy = new HttpRequestProxy();
			String reqUrl=String.format(
					"http://api.weixin.qq.com/card/code/deposit?access_token=%s",
					WxUtils.GetAccessToken()); 
			Map parameters=new HashMap();
			obj.put("card_id","prCjajnQ1iPwjJHEZ0i8DbHYZgdo");
			obj.put("code", new String[]{code});
			String jsonResultStr = proxy.doJsonPost(reqUrl, parameters, obj.toString());
			JSONObject jsonResult=JSONObject.fromObject(jsonResultStr);
			System.out.println(jsonResult.getString("errmsg")+"|"+jsonResult.getString("errcode"));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
//	//激活卡
//	@RequestMapping("/ActivateCard") 
//	@ResponseBody 
//	public String activateCard(HttpServletRequest request) throws WexinReqException {
//		String result = "";
//		String card_id = "prCjajnQ1iPwjJHEZ0i8DbHYZgdo";
//		
//		String electronicCardNo = request.getSession().getAttribute("electronicCardNo")==null? "":request.getSession().getAttribute("electronicCardNo").toString();
//		 
//		//激活卡参数设置
//		Account account = commonService.loadAccount(electronicCardNo);
//		ActivateCard activateCard = new ActivateCard();
//		activateCard.setCard_id(card_id);
//		activateCard.setCode(electronicCardNo);
//		activateCard.setInit_balance(account.getBalance()==null?0:account.getBalance().floatValue());
//		activateCard.setInit_bonus(account.getBonus()==null?0:account.getBonus().floatValue());
//		//激活卡方法调用
//		return result;
//		
//	}
	/**
	 * 员工绑定页面
	 * @return
	 */
	@RequestMapping("/index/staffBinding")
	public String staffBinding() {
		return "ucenter/staffBinding";
	}
	
	/**
	 * 员工绑定ajax方法
	 * @param IDNumber
	 * @param staffno
	 * @return
	 */
	@RequestMapping("/index/bandStaffInfo")
	@ResponseBody
	public Result bandStaffInfo(String IDNumber,String staffno,HttpSession session){
		String strParams = "YGBD#";
		String openid = session.getAttribute("openid")+"";
		strParams = strParams+"#"+IDNumber+"#"+staffno+"#"+openid;
		Result res = new Result();
		boolean isok = commonService.bandStaffInfo(strParams);
		res.setIsok(isok);
		return res;
	}
	
	/**
	 * 我的账号
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/scan")
	public String scan(HttpSession session, Model model) {
		String openId = ObjectUtils.toString(session.getAttribute("openid"));
		if(StringUtils.isNotBlank(openId)){
			
		}
		return "ucenter/scan";
	}
	
	/**
	 * 获取随机数
	 * @return
	 */
	private String getRandomCode(){
		Random random = new Random();
	    StringBuffer code = new StringBuffer();
	    for(int i = 0; i < 6;i++) {
	    	code.append(Math.abs(random.nextInt())%10);
	    }
	    return code.toString();
	}
	
	
}
